<?php
class EditPictureCtl extends BaseCtl {
	public function EditPictureCtl(){
		parent::BaseCtl();
	}
	
	public function submit(){
		try {
			$form = $this->getEditPictureForm();
			$picturesForm = $this->getPicturesForm();
			
			$adding = $form->isAdding();
			
			$picture = new Picture();
			$picture->setId($form->getId());
			$picture->setAlbumId($form->getAlbumId());
			$picture->setComments($form->getName());
			
			$service = new Service();
			
			if($adding){
				$seq = $service->getMaxPictureSeq() + 10;
				$picture->setSeqNo($seq);
				
				// check the file is there and process it, if not, will trigger errors
				if($this->fileExists('picture')){
					$fl = $_FILES['picture'];
					$this->processFile($fl, $picture->getId());
				}
				else {
					throw new Exception('Please postback the file with the picture');
				}
				
				$service->addPicture($picture);
				$picturesForm->addPicture($picture);
			}
			else {
				// if file is there, update the file
				if($this->fileExists('picture')){
					$fl = $_FILES['picture'];
					$this->processFile($fl, $picture->getId());
				}
				
				$service->updatePicture($picture);
				$picturesForm->updatePicture($picture);
			}
			
			$this->redirect('pictures.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
	public function cancel(){
		try {
			$this->redirect('pictures.php');
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
    
	public function isPostback(){
		return 'editpicture' == $this->getPost('pagename');
	}

    public function loadData(){
    	$form = $this->getEditPictureForm();
    	
    	$form->setId($this->getPost('id'));
    	$form->setAdding('yes' == $this->getPost('adding'));
    	$form->setName($this->getPost('name'));
    	
    	$form->setAlbumId($this->getPost('albumId'));
    	$form->setAlbumName($this->getPost('albumName'));
    }
} 
?>